package com.fw.ui.view.settings.usercontrol.bouser.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.fw.service.bean.EntryBean;
import com.fw.service.bean.ErrorBean;
import com.fw.service.bouser.bean.BOUserBean;
import com.fw.ui.ApplicationUI;
import com.fw.ui.bao.BOUserBAO;
import com.fw.ui.bao.MasterDataBAO;
import com.fw.ui.bao.MessageBAO;
import com.fw.ui.bao.PropertyBAO;
import com.fw.ui.util.SessionInfoUtils;
import com.fw.ui.util.UICommonUtils;
import com.fw.ui.util.VaadinApplicationObjectSupport;
import com.fw.ui.view.common.ConfirmDialogWindow;
import com.fw.ui.view.event.AbstractButtonClickListener;
import com.fw.ui.view.settings.usercontrol.bouser.EditBOUserView;
import com.vaadin.ui.Button.ClickEvent;

@Component
@Scope(SCOPE_PROTOTYPE)
public class EditBOUserSaveButtonClickListener extends AbstractButtonClickListener {

    private static final long serialVersionUID = 1L;

    @Autowired
    protected transient VaadinApplicationObjectSupport app;
    @Autowired
    private BOUserBAO bOUserBAO;
    @Autowired
    private MessageBAO messageBAO;
    @Autowired
    private PropertyBAO propertyBAO;
    @Autowired
    private MasterDataBAO masterDataBAO;
    @Autowired
    private UICommonUtils uiCommonUtils;
    @Autowired
    private SessionInfoUtils sessionInfoUtils;

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> click(ClickEvent event) throws Exception {
	EditBOUserView editBOUserView = (EditBOUserView) this.getBasedComponent();

	String email = editBOUserView.getTxtEmail().getValue();
	String employeeId = editBOUserView.getTxtEmployeeId().getValue();
	String employeeName = editBOUserView.getTxtEmployeeName().getValue();
	String role = (String) editBOUserView.getCbbGroup().getValue();
	String status = (String) editBOUserView.getCbbStatus().getValue();

	BOUserBean oldBoUserBean = editBOUserView.getBoUserBean();

	BOUserBean boUserBean = new BOUserBean();
	boUserBean.setId(oldBoUserBean.getId());
	boUserBean.setUsername(oldBoUserBean.getUsername());
	boUserBean.setEmail(email);
	boUserBean.setEmployeeID(employeeId);
	boUserBean.setEmployeeName(employeeName);
	boUserBean.setRole(role);
	boUserBean.setStatus(status);

	ApplicationUI applicationUI = (ApplicationUI) editBOUserView.getUI();
	sessionInfoUtils.setSessionInfoDetails(boUserBean, applicationUI.getAuthenticationBean(), applicationUI.getLocale());

	Map<String, Serializable> mapResult = this.bOUserBAO.updateBOUser(boUserBean);
	Map<String, Object> result = new HashMap<String, Object>();
	if (mapResult != null) {
	    List<ErrorBean> errorBeans = (List<ErrorBean>) mapResult.get(List.class.getName() + "." + ErrorBean.class.getName());
	    BOUserBean resultBOUserBean = (BOUserBean) mapResult.get(BOUserBean.class.getName());
	    if (errorBeans != null && !errorBeans.isEmpty()) {
		result.put(MessageBAO.MESSAGE_WARNING_TYPE, errorBeans);
	    } else {
		if (resultBOUserBean != null && resultBOUserBean.getId() != null) {
		    editBOUserView.setBoUserBean(resultBOUserBean);

		    uiCommonUtils.setValueUIComponent(editBOUserView.getTxtUsername(), resultBOUserBean.getUsername());
		    uiCommonUtils.setValueUIComponent(editBOUserView.getTxtEmail(), resultBOUserBean.getEmail());
		    uiCommonUtils.setValueUIComponent(editBOUserView.getTxtEmployeeId(), resultBOUserBean.getEmployeeID());
		    uiCommonUtils.setValueUIComponent(editBOUserView.getTxtEmployeeName(), resultBOUserBean.getEmployeeName());
		    uiCommonUtils.setValueUIComponent(editBOUserView.getCbbGroup(), resultBOUserBean.getRole());
		    uiCommonUtils.setValueUIComponent(editBOUserView.getCbbStatus(), resultBOUserBean.getStatus());

		    uiCommonUtils.clearAllUIComponentNoInputFieldWithPrefix(editBOUserView);

		    List<EntryBean<String, String>> statuses = masterDataBAO
			    .selectBOUserStatusByCurrentStatus(resultBOUserBean.getStatus());
		    if (statuses != null && !statuses.isEmpty()) {
			editBOUserView.getCbbStatus().removeAllItems();
			for (EntryBean<String, String> entry : statuses) {
			    editBOUserView.getCbbStatus().addItem(entry.getKey());
			    editBOUserView.getCbbStatus().setItemCaption(entry.getKey(), entry.getValue());
			}
			editBOUserView.getCbbStatus().setValue(resultBOUserBean.getStatus());
			editBOUserView.getCbbStatus().select(resultBOUserBean.getStatus());
		    }

		    String activeStatus = propertyBAO
			    .getPropertyValue("com.fw.ui.view.settings.usercontrol.bouser.EditBOUserView.exclude.status.item.active");
		    if (!activeStatus.equals(resultBOUserBean.getStatus())) {
			uiCommonUtils.setEnableUIComponent(editBOUserView.getBtnResetPassword(), false);
		    } else {
			uiCommonUtils.setEnableUIComponent(editBOUserView.getBtnResetPassword(), true);
		    }

		    String closeStatus = propertyBAO
			    .getPropertyValue("com.fw.ui.view.settings.usercontrol.bouser.EditBOUserView.exclude.status.item.closed");
		    if (closeStatus.equals(resultBOUserBean.getStatus())) {
			this.setAutoEnabled(false);
			List<com.vaadin.ui.Component> componentsEnable = new ArrayList<com.vaadin.ui.Component>();
			componentsEnable.add(editBOUserView.getBtnCancel());
			uiCommonUtils.setEnableAllUIComponent(editBOUserView, componentsEnable, false);
		    }

		    if (activeStatus.equals(resultBOUserBean.getStatus()) && !activeStatus.equals(oldBoUserBean.getStatus())) {
			String title = messageBAO.getMessage("message.dialog.title.info");
			String[] params = new String[] { resultBOUserBean.getPassword() };
			String content = messageBAO.getMessageWithParams(
				"com.fw.ui.view.settings.usercontrol.bouser.EditBOUserView.message.updated.resetpassword", params);
			String okCaption = messageBAO.getMessage("application.button.ok.caption");

			ConfirmDialogWindow.createConfirmDialog(editBOUserView.getUI(), title, content, okCaption, null, "130px", "500px");
			return null;
		    }

		    result.put(MessageBAO.MESSAGE_INFO_TYPE, "com.fw.ui.view.settings.usercontrol.bouser.EditBOUserView.message.updated");
		} else {
		    result.put(MessageBAO.MESSAGE_WARNING_TYPE, "com.fw.ui.view.settings.usercontrol.bouser.EditBOUserView.message.failed");
		}
	    }
	} else {
	    result.put(MessageBAO.MESSAGE_WARNING_TYPE, "message.error.common");
	}

	return result;
    }

    @Override
    public boolean validate(ClickEvent event) {
	EditBOUserView editBOUserView = (EditBOUserView) this.getBasedComponent();
	try {

	    uiCommonUtils.clearAllUIComponentNoInputFieldWithPrefix(editBOUserView);

	    boolean usernameValid = editBOUserView.getTxtUsername().isValid();
	    boolean emailValid = editBOUserView.getTxtEmail().isValid();
	    boolean employeeIdValid = editBOUserView.getTxtEmployeeId().isValid();
	    boolean employeeNameValid = editBOUserView.getTxtEmployeeName().isValid();
	    boolean groupValid = editBOUserView.getCbbGroup().isValid();
	    boolean statusValid = editBOUserView.getCbbStatus().isValid();

	    if (usernameValid && emailValid && employeeIdValid && employeeNameValid && groupValid) {
		return true;
	    } else {
		if (!usernameValid) {
		    editBOUserView.getTxtUsername().addStyleName("v-textfield-error");
		    if (editBOUserView.getTxtUsername().getErrorMessage() != null) {
			editBOUserView.getLblUsernameValidateMessage().setValue(
				editBOUserView.getTxtUsername().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editBOUserView.getRow1Validate().setVisible(true);
		}

		if (!emailValid) {
		    editBOUserView.getTxtEmail().addStyleName("v-textfield-error");
		    if (editBOUserView.getTxtEmail().getErrorMessage() != null) {
			editBOUserView.getLblEmailValidateMessage().setValue(
				editBOUserView.getTxtEmail().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editBOUserView.getRow2Validate().setVisible(true);
		}

		if (!employeeIdValid) {
		    editBOUserView.getTxtEmployeeId().addStyleName("v-textfield-error");
		    if (editBOUserView.getTxtEmployeeId().getErrorMessage() != null) {
			editBOUserView.getLblEmployeeIdValidateMessage().setValue(
				editBOUserView.getTxtEmployeeId().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editBOUserView.getRow4Validate().setVisible(true);
		}

		if (!employeeNameValid) {
		    editBOUserView.getTxtEmployeeName().addStyleName("v-textfield-error");
		    if (editBOUserView.getTxtEmployeeName().getErrorMessage() != null) {
			editBOUserView.getLblEmployeeNameValidateMessage().setValue(
				editBOUserView.getTxtEmployeeName().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editBOUserView.getRow5Validate().setVisible(true);
		}

		if (!groupValid) {
		    editBOUserView.getCbbGroup().addStyleName("v-filterselect-error");
		    if (editBOUserView.getCbbGroup().getErrorMessage() != null) {
			editBOUserView.getLblGroupValidateMessage().setValue(
				editBOUserView.getCbbGroup().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editBOUserView.getRow6Validate().setVisible(true);
		}

		if (!statusValid) {
		    editBOUserView.getCbbStatus().addStyleName("v-filterselect-error");
		    if (editBOUserView.getCbbStatus().getErrorMessage() != null) {
			editBOUserView.getLblGroupValidateMessage().setValue(
				editBOUserView.getCbbStatus().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editBOUserView.getRow7Validate().setVisible(true);
		}
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    return false;
	}
	return false;
    }

}
